package com.expense.app.admin.services.job.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.app.admin.common.BaseService;
import com.expense.app.admin.model.dto.job.JobDTO;
import com.expense.app.admin.model.dto.job.JobImportDTO;
import com.expense.app.admin.model.dto.job.JobListDTO;
import com.expense.app.admin.model.dto.job.JobPageDTO;
import com.expense.app.admin.model.params.job.JobImportParam;
import com.expense.app.admin.model.params.job.xiao.JobsListParam;
import com.expense.app.admin.model.params.job.xiao.JobsParam;
import com.expense.app.admin.services.job.XiaoJobsServ;
import com.expense.common.constant.enums.DeletedStatus;
import com.expense.common.dao.job.XiaoJobCitysDao;
import com.expense.common.dao.job.XiaoJobsDao;
import com.expense.common.exception.PlatformException;
import com.expense.common.model.auth.AdminUser;
import com.expense.common.model.job.XiaoJobCitys;
import com.expense.common.model.job.XiaoJobs;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 西奥招聘
 */
@Service
public class XiaoJobsServImpl extends BaseService implements XiaoJobsServ {
    private static final Log log = LogFactory.get();

    @Autowired
    XiaoJobsDao xiaoJobsDao;
    @Autowired
    XiaoJobCitysDao xiaoJobCitysDao;


    @Override
    public JobImportDTO importExcel(JobImportParam param) {
        AdminUser loginUser = getCurrentUser();
        List<Map<String,String>> list = param.getMapList();
        List<Map<String,String>> errorList = new ArrayList<>();
        List<Map<String,String>> errorDataList = new ArrayList<>();
        //遍历所有的数据
        if(list != null && list.size()>0) {
            if("update".equals(param.getType())){
                xiaoJobsDao.deleteAll(loginUser.getId());
                xiaoJobCitysDao.deleteAll(loginUser.getId());
            }

            List<XiaoJobs> jobList = new ArrayList<>();
            for (Map<String, String> map : list) {
                int index = list.indexOf(map);
                String sort = map.get("序号");
                String jobType = map.get("岗位分类");
                String jobName = map.get("岗位名称");
                String jobCategory = map.get("职位性质");
                String dept = map.get("所属部门");
                String workPlace = map.get("工作地点");
                String salary = map.get("薪资");
                String jobDesc = map.get("职位说明");
                String requirement = map.get("岗位要求");
                String city = map.get("招聘城市");
                String applyUrl = map.get("猎聘链接");

                //返回错误记录
                Map<String, String> errorData = new HashMap<>();
                errorData.put("sort", sort);
                errorData.put("jobType", jobType);
                errorData.put("jobName", jobName);
                errorData.put("jobCategory", jobCategory);
                errorData.put("dept", dept);
                errorData.put("workPlace", workPlace);
                errorData.put("salary", salary);
                errorData.put("jobDesc", jobDesc);
                errorData.put("requirement", requirement);
                errorData.put("city", city);
                errorData.put("applyUrl", applyUrl);

                XiaoJobs entity = new XiaoJobs();
                // 序号不能为空
                if (StrUtil.isBlank(sort)) {
                    String reason = "序号不能为空";
                    errorList.add(genErrorMap(index, "序号", sort, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(jobType)) {
                    String reason = "岗位分类不能为空";
                    errorList.add(genErrorMap(index, "岗位分类", jobType, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(jobName)) {
                    String reason = "岗位名称不能为空";
                    errorList.add(genErrorMap(index, "岗位名称", jobName, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(jobCategory)) {
                    String reason = "职位性质不能为空";
                    errorList.add(genErrorMap(index, "职位性质", jobCategory, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(city)) {
                    String reason = "招聘城市不能为空";
                    errorList.add(genErrorMap(index, "招聘城市", city, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }
                if (StrUtil.isBlank(applyUrl)) {
                    String reason = "猎聘链接不能为空";
                    errorList.add(genErrorMap(index, "猎聘链接", city, reason));
                    errorDataList.add(genErrorDataMap(errorData, reason));
                    continue;
                }

                setBaseInfo(entity);
                entity.setSort(Convert.toInt(sort,99999));
                entity.setJobType(jobType);
                entity.setJobName(jobName);
                entity.setJobCategory(jobCategory);
                entity.setDept(dept);
                entity.setWorkPlace(workPlace);
                entity.setSalary(salary);
                entity.setJobDesc(jobDesc);
                entity.setRequirement(requirement);
                entity.setCity(city);
                entity.setApplyUrl(applyUrl);
                jobList.add(entity);
            }
            if(jobList.size()>0) {
                List<XiaoJobCitys> cityList = new ArrayList<>();
                jobList.forEach(job ->{
                    xiaoJobsDao.insertTemplate(job, true);

                    XiaoJobCitys model = new XiaoJobCitys();
                    setBaseInfo(model);
                    model.setJobId(job.getId());
                    String city = job.getCity();
                    int index = city.lastIndexOf("市");
                    if(index>-1 && index == city.length()-1 ){
                        city = city.substring(0,index);
                    }
                    model.setCity(city);
                    model.setApplyUrl(job.getApplyUrl());
                    cityList.add(model);
                });
                xiaoJobCitysDao.saveAll(cityList);
            }
        }
        JobImportDTO dto = new JobImportDTO();
        dto.setTotalCount(list.size());
        dto.setSuccessCount(list.size() - errorList.size());
        dto.setErrorCount(errorList.size());
        dto.setErrorList(errorList);
        dto.setErrorDataList(errorDataList);
        return dto;
    }

    @Override
    public JobListDTO findList(JobsListParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",param.getKey());
        condition.put("jobType",param.getJobType());
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort());
        pageQuery.setParas(condition);
        xiaoJobsDao.findListPage(pageQuery);
        return new JobListDTO(pageQuery.getList(),pageQuery.getTotalRow());
    }

    @Override
    public JobPageDTO findInitList() {
        List<String> jobTypeList = xiaoJobsDao.findJobTypeList();
        return JobPageDTO.builder().jobTypeList(jobTypeList).build();
    }

    @Override
    public XiaoJobs findOne(Long id) {
        return xiaoJobsDao.findByIdAndDeleted(id);
    }

    @Override
    public JobDTO findDetail(Long id) {
        XiaoJobs entity = xiaoJobsDao.findByIdAndDeleted(id);
        if(null != entity){
            entity.setXiaoJobCitys(xiaoJobCitysDao.findByJobId(id));
        }
        return new JobDTO(entity);
    }

    @Override
    public XiaoJobs saveOne(JobsParam param) {
        XiaoJobs entity = param.getEntity();
        setBaseInfo(entity);
        if(null != entity.getId()){
            XiaoJobCitys city = entity.getXiaoJobCitys();
            setBaseInfo(city);
            xiaoJobCitysDao.saveOne(city);
        }
        xiaoJobsDao.saveOne(entity);
        //其他关联处理
        return entity;
    }

    @Override
    public Long deleteOne(Long id) {
        XiaoJobs entity = xiaoJobsDao.findByIdAndDeleted(id);
        if(entity == null) throw new PlatformException("西奥招聘已不存在");
        entity.setDeleted(DeletedStatus.DELETED);
        setBaseInfo(entity);
        xiaoJobsDao.updateTemplateById(entity);
        //其他关联处理
        return id;
    }

    /**
     * 生成错误返回map
     * @param index 错误所在行索引,从0开始
     * @param field 错误列名
     * @param fieldValue 错误列值
     * @param reason 错误说明
     * @return
     */
    public Map<String,String> genErrorMap(Integer index,String field,String fieldValue,String reason){
        Map<String, String> exit = new HashMap<>();
        exit.put("index", (index+1)+"");
        exit.put("field", field);
        exit.put("val",fieldValue);
        exit.put("reason", reason);
        return exit;
    }
    public Map<String,String> genErrorDataMap(Map<String,String> errorData,String reason){
        errorData.put("reason", reason);
        return errorData;
    }
}
